package com.wing.productionPlan.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.productionPlan.model.entity.DayTakeGoods;
import com.wing.productionPlan.model.entity.DayTakeGoodsIterm;
import com.wing.productionPlan.model.response.DayTakeGoodsVO;
import com.wing.productionPlan.service.DayTakeGoodsItermService;
import com.wing.productionPlan.service.DayTakeGoodsService;
import com.wing.web.excel.DayTakeGoodsExcelln;
import com.wing.web.excel.DownExcelUtil;
import com.wing.web.excel.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Validated
@Api(value = "Admin-生产管理-日提货订单", tags = "#/product/requirePlan/dayTakeGoodsList")
@RestController("DayTakeGoodsController")
@RequestMapping("productionPlan/admin/dayTakeGoods")
@RequiredArgsConstructor
public class DayTakeGoodsController {

    private final DayTakeGoodsService dayTakeGoodsService;

    private final  DayTakeGoodsItermService dayTakeGoodsItermService;

    @ApiOperation(value = "查询日提货订单列表", notes = "搜索列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<DayTakeGoodsVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,String takeOrderNumber
            ,String factoryName
            ,String startCreateTime
            ,String endCreateTime
    ) {
        Page<DayTakeGoodsVO> pg = new Page<>(page, limit);
        HashMap map = new HashMap();
        map.put("takeOrderNumber", takeOrderNumber);
        map.put("factoryName", factoryName);
        if (com.alibaba.nacos.common.utils.StringUtils.isNotBlank(startCreateTime)) {
            map.put("startCreateTime", startCreateTime);
        }
        if (com.alibaba.nacos.common.utils.StringUtils.isNotBlank(endCreateTime)) {
            map.put("endCreateTime", endCreateTime);
        }
        Page<DayTakeGoodsVO> list = dayTakeGoodsService.pageList4app(pg, map);
        List<DayTakeGoodsVO> records = list.getRecords();

        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "查询需求计划详情", notes = "搜索详情")
    @GetMapping("/getDayTakeGoodsDetail")
    public JsonResult getDayTakeGoodsDetail(@RequestParam("id") Long id) {
        DayTakeGoodsVO appById = dayTakeGoodsService.get4appById(id);
        if(appById!=null){
            /*appById.setAuditStatusText(AuditStatusEnum.getDescriptionByCode(appById.getAuditStatus()));*/
            // 创建 LambdaQueryWrapper
            LambdaQueryWrapper<DayTakeGoodsIterm> wrapper = Wrappers.<DayTakeGoodsIterm>lambdaQuery()
                    .eq(DayTakeGoodsIterm::getTakeGoodsId, appById.getId());

            // 使用服务层的 list 方法进行查询
            List<DayTakeGoodsIterm> requirePlanItemList = dayTakeGoodsItermService.list(wrapper);

            appById.setDayTakeGoodsItermList(requirePlanItemList);
            return JsonResult.success(appById);
        }else{
            return JsonResult.fail("未发现详情数据！");
        }
    }


    @ApiOperation(value = "下载产品数据录入excel模板")
    @GetMapping("/template")
    public void template(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String[] headerArr = {"行标签","物料简码","组件描述","plantCode","采购组织","工厂名称","生产线",
                "采购组描述","供应商回复","供应商","合计","在制","月份","日期","提货数","备注"};
        List<String[]> downData = new ArrayList<>();
        DownExcelUtil.createExcelTemplate(response, request, "日排计划-邮件格式导入模板", Arrays.asList(headerArr),downData, null);
    }


    @PostMapping("/importExcel")
    public JsonResult importExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return JsonResult.fail("上传文件为空！");
        }
        try {
            //获取原始的文件名
            ExcelUtil<DayTakeGoodsExcelln> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<DayTakeGoodsExcelln> list = reader.read(is,DayTakeGoodsExcelln.class);

            if (CollectionUtils.isEmpty(list)) {
                return JsonResult.fail("请在表格中添加数据！");
            }
            dayTakeGoodsService.importExcel(list);
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("上传文件异常！异常信息:", e);
            return JsonResult.exception("上传文件异常！异常信息:" + e.getMessage());
        }
        return JsonResult.success("上传成功！");
    }


    @ApiOperation(value = "添加需求计划表", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/saveDayTakeGoods")
    public JsonResult saveDayTakeGoods(@RequestBody DayTakeGoods dayTakeGoods) {
        //添加相关校验
        if(StringUtils.isEmpty(dayTakeGoods.getFactoryName())){
            return JsonResult.fail("请完善表格中数据！");
        }
        if(StringUtils.isEmpty(dayTakeGoods.getPlantCode())){
            return JsonResult.fail("请完善表格中数据！");
        }
        if(dayTakeGoods.getDayTakeGoodsItermList().size()<=0){
            return JsonResult.fail("请添加订单明细数据！");
        }
        //todo 相关生产物料添加是否校验
        return  dayTakeGoodsService.saveDayTakeGoods(dayTakeGoods);
    }

    @ApiOperation(value = "修改需求计划表", notes = "修改")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/updateDayTakeGoods")
    public JsonResult updateDayTakeGoods(@RequestBody DayTakeGoods dayTakeGoods) {
        //添加相关校验
        if(StringUtils.isEmpty(dayTakeGoods.getFactoryName())){
            return JsonResult.fail("请完善表格中数据！");
        }
        if(StringUtils.isEmpty(dayTakeGoods.getPlantCode())){
            return JsonResult.fail("请完善表格中数据！");
        }
        if(dayTakeGoods.getDayTakeGoodsItermList().size()<=0){
            return JsonResult.fail("请添加订单明细数据！");
        }
         return  dayTakeGoodsService.updateDayTakeGoods(dayTakeGoods);
    }




}
